<script setup lang="ts">
import CdlDescriptions from "@/components/descriptions";
import CdlBill from "@/components/bill"
import {ref, h} from "vue";
import type {DescriptionsTree} from "@/interfaces/components/Descriptions";
import type {WayBill, Check} from "@/interfaces/views/task/task";
import CdlTable from "@/components/table";
import CdlForm from "@/components/form"
import CdlImage from "@/components/Image"
import Trajectory from "@/components/gps/trajectory.vue";
import Track from "@/components/gps/track.vue";
import {TableTree} from "@/interfaces/components/Table";
import {Bill} from "@/interfaces/views/project/bill";
import {useRoute, useRouter} from "vue-router";
import {useTaskWayBillAbandonApi, useTaskWayBillInfoApi, useTaskWayBillSettlementApi} from "@/api/project/task";
import {createPopup} from "@/utils/createPopup";
import {FormTree} from "@/interfaces/components/Form";
import {FormData, Mode} from "@/interfaces/components/Page";
import {cloneDeep} from "lodash";
import {mergeObjects} from "@/utils/utilities";
import constant from "@/utils/constant";
import {ElMessage, ElMessageBox} from "element-plus";

const route = useRoute()
const router = useRouter()
const loading = ref(true)
init()

const baseDescriptionsTree: DescriptionsTree<WayBill> = [
  {label: "运单号", prop: "id"},
  {label: "运单类型", prop: "type", dict: "waybill_type"},
  {label: "运单状态", prop: "state", dict: "waybill_state"},
  {label: "是否结算", prop: "settlementStatus", dict: "waybill_settlementStatus"},
  {label: "所属订单名称", prop: "projectName"},
  {label: "所属任务名称", prop: "taskName", span: 2},
  {label: "运单支出", prop: ""},
  {label: "运单收入", prop: ""},
  {label: "关联司机", prop: "driverName"},
  {label: "关联车辆", prop: "car"},
  {label: "创建人", prop: "createName"},
  {label: "信用评分", prop: ""},
  {label: "装货查验", prop: "acceptType", slot: (val)=>{
      let text = ""
      if(val === 0 || val === 2) text = "无需上传装货查验"
      else text = shipmentData.value.id !== undefined? "已上传" : "未上传"
      console.log(shipmentData.value)
      return h("span", text)
    }},
  {label: "卸货查验", prop: "acceptType", slot: (val)=>{
      let text = ""
      if(val === 0 || val === 1) text = "无需上传卸货查验"
      else text = unloadData.value.id !== undefined? "已上传" : "未上传"
      return h("span", text)
    }},
  {label: "接单时间", prop: "startTime"},
  {label: "完成时间", prop: "endTime"}
]
const baseDescriptionsData = ref<FormData<WayBill>>({})
const wayBillFormTree: FormTree<WayBill> = [
  [
    {label: "运单号", component: "input", prop: "id", disabled: true},
    {label: "运单状态", component: "input", prop: "id", disabled: true},
  ],
  [
    {label: "关联任务", component: "input", prop: "taskName", disabled: true},
  ],
  [
    {label: "关联司机", component: "select", prop: "taskCarId", serviceOptionKey: "associationDriver",
      optionProps: {label: "name", value: "id"}
      , rule:[{
        required: true, message: '关联司机不能为空', trigger: 'blur'
      }]},
    {label: "创建人", component: "input", prop: "createName", disabled: true},
  ],
  [
    {label: "接单时间", component: "datePicker", prop: "startTime", type: "datetime", rule:[{
        required: true, message: '接单时间不能为空', trigger: 'blur'
      }]},
    {label: "完成时间", component: "datePicker", prop: "endTime", type: "datetime", rule:[{
        required: true, message: '完成时间不能为空', trigger: 'blur'
      }]}
  ],
  [
    {label: "备注", component: "input", type: "textarea", prop: "remark", style: "width: 100%"},
  ]
]
const wayBillFormData: FormData<WayBill> = {
  taskId: "",
  taskCarId: "",
  startTime: "",
  endTime: "",
  createName: "",
  remark: ""
}

const billData = ref<Bill[]>([])
const billTabTree: TableTree<Bill> = {
  colRule: [
    {ti: "账单名称"},
    {ti: "账单类型"},
    {ti: "金额"},
    {ti: "收入/支出"},
    {ti: "付款人姓名"},
  ],
  control: [
    {name: "详情", type: "info", method: ()=> {}, auth: "project:task:info"},
    {name: "删除", type: "danger", method: ()=> {}, auth: "project:task:delete"},
  ]
}
const shipmentAndUnloadTree: DescriptionsTree<Check> = [
  {label: "状态", prop: "state", dict: "global_state"},
  {label: "说明", prop: "remark"},
  {label: "图片", prop: "pic", slot: (id) =>{
      return h(CdlImage, {
        previewSrcList: [constant.downloadUrl + id],
        src: constant.downloadUrl + id,
      })
    }},
  {label: "上传时间", prop: "createTime"},
]

const shipmentData = ref<FormData<Check>>({})
const unloadData = ref<FormData<Check>>({})

/**
 * 新建账单
 */
function openCreateBill(){
  createPopup("新建账单", h(CdlBill, {
    types: [1]
  }), "add", popupCallBack)
}

function init(){
  useTaskWayBillInfoApi(route.query.id as string | number).then(res =>{
    const {checks, ...rest} = res.data
    baseDescriptionsData.value = rest
    checks?.forEach((item: any) =>{
      if(item.type === 1) shipmentData.value = item
      else if(item.type === 2) unloadData.value = item
    })
    loading.value = false
  })
}

function openTrajectoryAnalysis(){
  createPopup("查看轨迹", h(Trajectory, {
    plateNum: baseDescriptionsData.value.car
  }))
}

function openTrajectoryTracking(){
  console.log("轨迹跟踪")
  createPopup("轨迹跟踪", h(Track))
}

function openCreateWayBillUpdate(data: any){
  createPopup("编辑运单", h(CdlForm, {
    templateTree: wayBillFormTree,
    model: createFormDataTemplate(data)
  }), "update")
}

/**
 * 结算
 */
function settlementHandle(){
  openCreateBill()
  // ElMessageBox.confirm(
  //     '确定要结算此运单吗，请继续?',
  //     '警告',
  //     {
  //       confirmButtonText: '继续',
  //       cancelButtonText: '取消',
  //       type: 'warning',
  //     }
  // ).then(() => {
  //   useTaskWayBillSettlementApi(route.query.id as string).then(()=>{
  //     ElMessage({
  //       type: 'success',
  //       message: '结算成功！',
  //     })
  //     init()
  //   })
  // }).catch(() => {
  //   ElMessage({
  //     type: 'info',
  //     message: '已取消',
  //   })
  // })
}
const scoreTree: FormTree<any> = [
    [
      {label: "星级", }
    ]
]

/**
 * 评价窗口
 */
// function openReview(){
//   createPopup("填写评分", h(CdlForm, {
//     templateTree:
//   }))
// }

/**
 * 废弃
 */
function discardHandle(){
  ElMessageBox.confirm(
      '确定要废弃此运单吗，请继续?',
      '警告',
      {
        confirmButtonText: '继续',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    useTaskWayBillAbandonApi(route.query.id as string).then(()=>{
      ElMessage({
        type: 'success',
        message: '已废弃！',
      })
      init()
    })
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消',
    })
  })
}

/**
 * 数据预处理
 * @param data
 */
function createFormDataTemplate(data: WayBill){
  let obj = cloneDeep(wayBillFormData)
  mergeObjects(obj, data)
  return obj
}
/**
 * 回调处理
 * @param mode
 * @param data
 */
function popupCallBack(mode: Mode, data: any){
  switch (mode){
    case "add":
      console.log(data)
      break
  }
}
/**
 * 回退页面
 */
function fallbackPage(){
  router.back()
}
</script>

<template>
  <el-card style="position: relative">
    <button class="back_btn" @click="fallbackPage"></button>
    <div class="main_control">
      <el-button type="primary" @click="openTrajectoryAnalysis" v-if="baseDescriptionsData.state === 2">轨迹分析</el-button>
      <el-button type="primary" @click="openTrajectoryTracking" v-if="baseDescriptionsData.state === 1">轨迹跟踪</el-button>
      <el-button type="danger" @click="settlementHandle"
                 v-if="baseDescriptionsData.settlementStatus === 1 && baseDescriptionsData.state === 2">结算</el-button>
      <el-button type="danger" @click="discardHandle">废弃</el-button>
      <el-button type="info" @click="openReview" v-if="baseDescriptionsData.settlementStatus === 2">评价</el-button>
    </div>
    <h1 class="top_line">基本信息</h1>
    <el-divider></el-divider>
    <CdlDescriptions :model="baseDescriptionsData" :template-tree="baseDescriptionsTree"
                     :column="4"></CdlDescriptions>
    <h1 class="top_line">关联账单</h1>
    <el-divider></el-divider>
    <CdlTable :data="billData" :template-tree="billTabTree" controlFixed></CdlTable>
  </el-card>
</template>

<style scoped lang="scss">

</style>
